
from django.shortcuts import render,redirect
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyForm,PrettyEditForm
from app01 import models

def pretty_list(request):


    """ 靓号列表 """
    # 根据用户响应访问的页码，计算出气质位置
    data_dict = {}
    cearch_data = request.GET.get('phone',"")
    if cearch_data:
        data_dict['phone__contains'] = cearch_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request,queryset)
    context = {
        "cearch_data": cearch_data, # 筛选条件
        'data_list': page_object.page_queryset, # 分页后的数据
        "page_string": page_object.html  # 页码
    }

    return render(request,'pretty_list.html',context)

def pretty_add(request):
    if request.method == 'GET':
        form = PrettyForm()
        return render(request,"pretty_add.html",{"form":form})

    form = PrettyForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list")
    return render(request,"pretty_add.html",{"form":form})



def pretty_edit(request,nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyForm(instance=row_object)
        return render(request,"pretty_edit.html",{"form":form})
    row_object = models.PrettyNum.objects.filter(id= nid).first()
    form = PrettyEditForm(data=request.POST,instance=row_object)
    if form.is_valid(): # 校验用户提交的数据是否合法
        form.save()
        return redirect('/pretty/list')
    return render(request,'pretty_edit.html',{'form':form})


def pretty_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list')
